/*
 * @Descripttion: 编辑任务对话框
 * @Author: 毕怀智
 * @Date: 2022-01-20 20:36:52
 * @Function: 该文件用途描述
 */

import { Button, DatePicker, Form, Input, Modal } from "antd";
import { useForm } from "antd/es/form/Form";
import moment from "moment";
import { useEffect } from "react";

import { useDeleteTask, useEditTask } from "api/Task";
import { TaskTypeSelect } from "components/TaskTypeSelect";
import { UserSelect } from "components/UserSelect";

import { useTaskModal, useTasksQueryKey } from "../utils";

const { RangePicker } = DatePicker;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

export const EditTask = () => {
  const { editingTaskId, editingTask, close } = useTaskModal();
  const [form] = useForm();
  const { mutateAsync: editTask, isLoading: editLoading } = useEditTask(
    useTasksQueryKey()
  );
  const { mutate: deleteTask } = useDeleteTask(useTasksQueryKey());

  const onCancel = () => {
    form.resetFields();
    close();
  };

  const onOk = async () => {
    await editTask({ ...editingTask, ...form.getFieldsValue() });
    close();
  };

  const onDelete = () => {
    close();
    Modal.confirm({
      okText: "确定",
      cancelText: "取消",
      title: "确定删除任务吗",
      onOk() {
        return deleteTask({ id: Number(editingTaskId) });
      },
    });
  };

  useEffect(() => {
    console.log(editingTask, "editingTask");

    if (editingTask?.time) {
      editingTask.time = [
        moment(editingTask?.time?.[0]),
        moment(editingTask?.time?.[1]),
      ];
    }
    form.setFieldsValue({ ...editingTask });
  }, [form, editingTask]);

  return (
    <Modal
      forceRender={true}
      onCancel={onCancel}
      confirmLoading={editLoading}
      title={"编辑任务"}
      visible={!!editingTaskId}
      footer={[
        <Button key={"delete"} onClick={onDelete}>
          删除
        </Button>,
        <Button key={"confirm"} onClick={onOk} type="primary">
          确认
        </Button>,
      ]}
    >
      <Form {...layout} form={form}>
        <Form.Item
          label={"任务名"}
          name={"name"}
          rules={[{ required: true, message: "请输入任务名" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label={"经办人"} name={"processorId"}>
          <UserSelect defaultValues={"经办人"} />
        </Form.Item>
        <Form.Item label={"类型"} name={"typeId"}>
          <TaskTypeSelect />
        </Form.Item>
        <Form.Item label="计划时间" name="time">
          <RangePicker placeholder={["开始时间", "结束时间"]} />
        </Form.Item>
        <Form.Item label={"备注"} name={"note"}>
          <Input.TextArea autoSize={{ minRows: 3, maxRows: 5 }} />
        </Form.Item>
      </Form>
      {/* <div style={{ textAlign: "right" }}>
        <Button onClick={onDelete} style={{ fontSize: "14px" }} size={"small"}>
          删除
        </Button>
      </div> */}
    </Modal>
  );
};
